var handlerDis, handlerArea, handlerHeight, handlerDisTerrain;
var clampMode = 0; // 空间模式
function measureInit() {
    //初始化测量距离
    handlerDis = new Cesium.MeasureHandler(viewer, Cesium.MeasureMode.Distance, clampMode);
    //注册测距功能事件
    handlerDis.measureEvt.addEventListener(function(result) {
        var dis = Number(result.distance);
        var distance = dis > 1000 ? (dis / 1000).toFixed(2) + 'km' : dis.toFixed(2) + 'm';
        handlerDis.disLabel.text = '距离:' + distance;
    });
    handlerDis.activeEvt.addEventListener(function(isActive) {
        if (isActive == true) {
            viewer.enableCursorStyle = false;
            viewer._element.style.cursor = '';
            $('body').removeClass('measureCur').addClass('measureCur');
        } else {
            viewer.enableCursorStyle = true;
            $('body').removeClass('measureCur');
        }
    });

    //初始化测量面积
    handlerArea = new Cesium.MeasureHandler(viewer, Cesium.MeasureMode.Area, clampMode);
    handlerArea.measureEvt.addEventListener(function(result) {
        var mj = Number(result.area);
        var area = mj > 1000000 ? (mj / 1000000).toFixed(2) + 'km²' : mj.toFixed(2) + '㎡'
        handlerArea.areaLabel.text = '面积:' + area;
    });
    handlerArea.activeEvt.addEventListener(function(isActive) {
        if (isActive == true) {
            viewer.enableCursorStyle = false;
            viewer._element.style.cursor = '';
            $('body').removeClass('measureCur').addClass('measureCur');
        } else {
            viewer.enableCursorStyle = true;
            $('body').removeClass('measureCur');
        }
    });

    //初始化测量高度
    handlerHeight = new Cesium.MeasureHandler(viewer, Cesium.MeasureMode.DVH);
    handlerHeight.measureEvt.addEventListener(function(result) {
        var distance = result.distance > 1000 ? (result.distance / 1000).toFixed(2) + 'km' : result.distance + 'm';
        var vHeight = result.verticalHeight > 1000 ? (result.verticalHeight / 1000).toFixed(2) + 'km' : result.verticalHeight + 'm';
        var hDistance = result.horizontalDistance > 1000 ? (result.horizontalDistance / 1000).toFixed(2) + 'km' : result.horizontalDistance + 'm';
        //handlerHeight.disLabel.text = '空间距离:' + distance;
        handlerHeight.vLabel.text = '垂直高度:' + vHeight;
        handlerHeight.hLabel.text = '水平距离:' + hDistance;
    });
    handlerHeight.activeEvt.addEventListener(function(isActive) {
        if (isActive == true) {
            viewer.enableCursorStyle = false;
            viewer._element.style.cursor = '';
            $('body').removeClass('measureCur').addClass('measureCur');
        } else {
            viewer.enableCursorStyle = true;
            $('body').removeClass('measureCur');
        }
    });

    //measureLineSpace();
}

function measureLineSpace() {
    var me = this;
    // 取消双击事件-追踪该位置
    viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);

    handlerDisTerrain = new Cesium.ScreenSpaceEventHandler(viewer.scene._imageryLayerCollection);
    var positions = [];
    var poly = null;
    var distance = 0;
    var cartesian = null;
    var floatingPoint;
    var labelPt;
    var measureIds = [];
    var options;

    handlerDisTerrain.setInputAction(function(movement) {
        cartesian = getPickPositionGlobe(movement.endPosition);
        if (!Cesium.defined(cartesian)) //跳出地球时异常
            return;
        if (positions.length >= 2) {
            if (!Cesium.defined(poly)) {
                poly = new PolyLinePrimitive(positions);
            } else {
                positions.pop();
                positions.push(cartesian);
            }
        }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    handlerDisTerrain.setInputAction(function(movement) {
        cartesian = getPickPositionGlobe(movement.position);
        if (!Cesium.defined(cartesian)) //跳出地球时异常
            return;

        if (positions.length == 0) {
            positions.push(cartesian.clone());
        }
        positions.push(cartesian);
        //记录鼠标单击时的节点位置，异步计算贴地距离
        labelPt = positions[positions.length - 1];
        if (positions.length > 2) {
            getSpaceDistance(positions);
        } else if (positions.length == 2) {
            //在三维场景中添加Label
            floatingPoint = viewer.entities.add({
                name: '空间距离',
                position: labelPt,
                point: {
                    pixelSize: 5,
                    color: Cesium.Color.RED,
                    outlineColor: Cesium.Color.WHITE,
                    outlineWidth: 2,
                }
            });
            measureIds.push(floatingPoint.id);
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

    handlerDisTerrain.setInputAction(function(movement) {
        handlerDisTerrain.destroy(); //关闭事件句柄
        handlerDisTerrain = undefined;
        positions.pop(); //最后一个点无效
        if (positions.length == 1)
            viewer.entities.remove(floatingPoint);
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);

    var PolyLinePrimitive = (function() {
        var self = this;

        function _(positions) {
            self.options = {
                name: '直线',
                polyline: {
                    show: true,
                    positions: [],
                    material: Cesium.Color.CHARTREUSE,
                    width: 5,
                    clampToGround: true
                }
            };
            positions = positions;
            _init();
        }

        function _init() {
            var _update = function() {
                return positions;
            };
            //实时更新polyline.positions
            self.options.polyline.positions = new Cesium.CallbackProperty(_update, false);
            var addedEntity = viewer.entities.add(self.options);
            measureIds.push(addedEntity.id);
        };

        return _;
    })();

    //空间两点距离计算函数
    function getSpaceDistance(positions) {
        //只计算最后一截，与前面累加
        //因move和鼠标左击事件，最后两个点坐标重复
        var i = positions.length - 3;
        var point1cartographic = Cesium.Cartographic.fromCartesian(positions[i]);
        var point2cartographic = Cesium.Cartographic.fromCartesian(positions[i + 1]);
        getTerrainDistance(point1cartographic, point2cartographic);
    }

    function getTerrainDistance(point1cartographic, point2cartographic) {
        var geodesic = new Cesium.EllipsoidGeodesic();
        geodesic.setEndPoints(point1cartographic, point2cartographic);
        var s = geodesic.surfaceDistance;
        var cartoPts = [point1cartographic];
        for (var jj = 1000; jj < s; jj += 1000) {　　 //分段采样计算距离
            var cartoPt = geodesic.interpolateUsingSurfaceDistance(jj);
            //                console.log(cartoPt);
            cartoPts.push(cartoPt);
        }
        cartoPts.push(point2cartographic);
        //返回两点之间的距离
        var promise = Cesium.sampleTerrain(viewer.terrainProvider, 8, cartoPts);
        Cesium.when(promise, function(updatedPositions) {
            // positions height have been updated.
            // updatedPositions is just a reference to positions.
            for (var jj = 0; jj < updatedPositions.length - 1; jj++) {
                var geoD = new Cesium.EllipsoidGeodesic();
                geoD.setEndPoints(updatedPositions[jj], updatedPositions[jj + 1]);
                var innerS = geoD.surfaceDistance;
                innerS = Math.sqrt(Math.pow(innerS, 2) + Math.pow(updatedPositions[jj + 1].height - updatedPositions[jj].height, 2));
                distance += innerS;
            }
            //在三维场景中添加Label
            var textDisance = distance.toFixed(2) + "米";
            if (distance > 10000)
                textDisance = (distance / 1000.0).toFixed(2) + "千米";
            floatingPoint = viewer.entities.add({
                name: '贴地距离',
                position: labelPt,
                point: {
                    pixelSize: 5,
                    color: Cesium.Color.RED,
                    outlineColor: Cesium.Color.WHITE,
                    outlineWidth: 2,
                },
                label: {
                    text: textDisance,
                    font: '18px sans-serif',
                    fillColor: Cesium.Color.GOLD,
                    style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                    outlineWidth: 2,
                    verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                    pixelOffset: new Cesium.Cartesian2(20, -20),
                }
            });
            measureIds.push(floatingPoint.id);
        });
    }
}

function clearAll() {
    handlerDis && handlerDis.clear();
    handlerArea && handlerArea.clear();
    handlerHeight && handlerHeight.clear();
    removeAllEntities();
}

function deactiveAll() {
    handlerDis && handlerDis.deactivate();
    handlerArea && handlerArea.deactivate();
    handlerHeight && handlerHeight.deactivate();
    handlerDisTerrain && handlerDisTerrain.deactivate();
}